package org.example.huadianguanli.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.example.core.constanct.CommonUtils;
import org.example.core.exception.ErrorException;
import org.example.core.mysql.SearchPageResult;
import org.example.core.mysql.Where;
import org.example.core.service.impl.SimpleServiceImpl;
import org.example.huadianguanli.entity.TOrderEntity;
import org.example.huadianguanli.model.TOrderModel;
import org.example.huadianguanli.model.TOrderShopModel;
import org.example.huadianguanli.model.TStorageModel;
import org.example.huadianguanli.model.TStorageShopModel;
import org.example.huadianguanli.service.TOrderService;
import org.example.huadianguanli.service.TOrderShopService;
import org.example.huadianguanli.service.TStorageService;
import org.example.huadianguanli.service.TStorageShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2024/2/14 20:17
 */
@Service
@Primary
public class TOrderServiceImpl extends SimpleServiceImpl<String, TOrderModel, TOrderEntity> implements TOrderService {

    @Autowired
    private TOrderShopService tOrderShopService;

    @Autowired
    private TStorageService tStorageService;

    @Autowired
    private TStorageShopService tStorageShopService;


    @Override
    public void create(Map<String, Object> params, String userId) {
        String id = CommonUtils.getUUID().replaceAll("-", "");
        TOrderModel orderModel = new TOrderModel();
        orderModel.setCode(generateCode());
        orderModel.setUserId(userId);
        orderModel.setStatus("0");
        orderModel.setId(id);
        add(orderModel);
        List<Map<String, Object>> shopList = (List<Map<String, Object>>) params.get("shopList");
        for (Map<String, Object> shopMap : shopList) {
            Object shopName = shopMap.get("shopName");
            Object storageId = shopMap.get("storageId");
            Object shopCount = shopMap.get("shopCount");
            List<TStorageShopModel> tStorageModelList = tStorageShopService.search(Where.build().field("storage_id").equal(storageId));
            int totalCount = 0;
            for (int tStorageIndex = 0; tStorageIndex < tStorageModelList.size(); tStorageIndex++) {
                TStorageShopModel tStorageShopModel = tStorageModelList.get(tStorageIndex);
                totalCount += tStorageShopModel.getCount();
            }
            if (totalCount == 0){
                throw new ErrorException("创建订单失败："+shopName+",库存不足！");
            }
            if(totalCount < (Integer) shopCount){
                throw new ErrorException("创建订单失败："+shopName+",库存剩余数量不足！");
            }
        }

        for (Map<String, Object> shopMap : shopList) {
            TOrderShopModel orderShopModel = new TOrderShopModel();
            Object shopName = shopMap.get("shopName");
            Object shopCount = shopMap.get("shopCount");
            Object shopPrice = shopMap.get("shopPrice");
            Object shopDiscountPrice = shopMap.get("shopDiscountPrice");
            Object shopType = shopMap.get("shopType");
            Object storageId = shopMap.get("storageId");

            orderShopModel.setOrderId(id);
            orderShopModel.setShopCount((Integer) shopCount);
            orderShopModel.setShopName((String) shopName);
            orderShopModel.setShopPrice(Double.parseDouble(shopPrice.toString()));
            orderShopModel.setShopDiscountPrice(Double.parseDouble(shopDiscountPrice.toString()));
            orderShopModel.setShopType((String) shopType);
            tOrderShopService.add(orderShopModel);
        }
    }

    @Override
    public SearchPageResult<cn.hutool.json.JSONObject> page(int page, int limit, String userId, String code) {
        SearchPageResult<cn.hutool.json.JSONObject> result = new SearchPageResult<>();
        Where where = Where.build().field("1").equal(1);
        if (!StringUtils.isEmpty(userId)) {
            where.and().field("user_id").equal(userId);
        }
        if (!ObjectUtils.isEmpty(code)) {
            where.and().field("code").like(code);
        }
        int totalCount = count(where);
        List<TOrderModel> search = search(where.limit(page, limit));
        JSONArray orderJsonArray = JSONArray.copyOf(search);
        List<cn.hutool.json.JSONObject> resultList = orderJsonArray.stream().map(o -> {
            cn.hutool.json.JSONObject orderJsonObject = JSONUtil.parseObj(o);
            Object id = orderJsonObject.get("id");
            List<TOrderShopModel> orderShopModelList =
                    tOrderShopService.search(Where.build().field("order_id").equal(id).and().field("del_flag").equal(0));
            orderJsonObject.set("shopList", orderShopModelList);
            return orderJsonObject;
        }).collect(Collectors.toList());
        result.setList(resultList);
        result.setTotalCount(totalCount);
        result.setPage(page);
        result.setLimit(limit);
        return result;
    }

    @Override
    public void pay(Map<String, Object> params) {
        Object orderId = params.get("orderId");
        TOrderModel orderModel = getById((String) orderId);
        orderModel.setStatus("1");
        update(orderModel);
    }

    @Override
    public void examine(Map<String, Object> params) {
        Object orderId = params.get("orderId");
        Object status = params.get("status");
        TOrderModel orderModel = getById((String) orderId);
        orderModel.setStatus((String) status);
        update(orderModel);
    }

    private String generateCode() {
        SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmss");
        String today = format.format(System.currentTimeMillis());
        int count = count(Where.build().field("create_time").betweenAnd(DateUtil.today() + " 00:00:00", DateUtil.today() + " 23:59:59"));
        return today + String.format("%03d", count);
    }
}
